<template>
  <base-content>
    <div class="row" style="width: 500px;margin: 0 auto;padding: 20px">
    <div class="row justify-center flex">
      <q-uploader
        style="width: 480px;margin-bottom: 20px"
        label="批量导入成绩（Excel）"
        multiple
        max-files="1"
        accept=".xls,.xlsx"
        :factory="factoryFn"
        @rejected="onRejected"
        @added="handleAdd"
        @start="handleUp"
      >
      </q-uploader>
    </div>
    <a :href="this.$PUBLIC_PATH + 'data/template.xlsx'" style="margin: 10px 0 20px 0">下载导入模板</a>
    <div class="justify-center flex">

      <div class="row">
     <q-form
    @submit="onSubmit"
    @reset="onReset"
    class="q-gutter-md"
    style="width: 500px"
  >
    <q-input
      filled
      v-model="studentNumber"
      label="请输入学号 *"
      lazy-rules
      :rules="[ val => val && val.length > 0 || '学号不能为空']"
    />
    <q-select
      name="preferred_genre"
      v-model="semesterPreferred"
      :options="semesterOption"
      :option-label="(item) => item === null ? null : item.semesterYear + ' ' + item.semesterType"
      :option-value="(item) => item === null ? null : item.semesterId"
      color="primary"
      filleds
      clearable
      label="请选择学期"
      style="width: 500px;"
    />
    <q-input
      filled
      v-model="week"
      label="请输入周数 *"
      lazy-rules
      :rules="[ val => val && val.length > 0 || '周数不能为空']"
    />
    <q-input
      filled
      v-model="typeId"
      label="请输入考勤类型 *"
      lazy-rules
      :rules="[ val => val && val.length > 0 || '考勤类型不能为空']"
    />
    <q-input
      filled
      v-model="times"
      label="请输入节数 *"
      lazy-rules
      :rules="[ val => val && val.length > 0 || '节数不能为空']"
    />
    <q-input
    filled
    v-model="note"
    label="请输入备注 *"
    lazy-rules
    :rules="[ val => val && val.length > 0 || '备注不能为空']"
  />

    <div>
      <q-btn label="提交" type="submit" color="primary"/>
      <q-btn label="重置" type="reset" color="primary" flat class="q-ml-sm" />
    </div>
  </q-form>
      </div>
    </div>
    </div>
  </base-content>
</template>

<script>
import BaseContent from '../../components/BaseContent/BaseContent'
import XLSX from 'xlsx'
import { Notify } from 'quasar'
export default {
  name: 'ClassAttend',
  components: { BaseContent },
  data () {
    return {
      semesterPreferred: { semesterId: '', semesterType: '', semesterYear: '' }, // 设置默认值为空
      semesterOption: [], // 这里是数据库返回的数据，数组里的对象用item标识
      studentNumber: null,
      semesterId: null,
      week: null,
      typeId: null,
      times: null,
      note: null,
      sheet: []
    }
  },
  mounted () {
    this.getAllSemesterYear()
  },
  methods: {
    handleAdd (files) {
      const fileReader = new FileReader()
      fileReader.onload = ev => {
        try {
          const data = ev.target.result
          const workbook = XLSX.read(data, {
            type: 'binary'
          })
          const wsname = workbook.SheetNames[0] // 取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) // 生成json表格内容
          this.sheet = ws
        } catch (e) {
          return false
        }
      }
      fileReader.readAsBinaryString(files[0])
    },
    factoryFn (files) {
      const fileReader = new FileReader()
      fileReader.onload = ev => {
        try {
          const data = ev.target.result
          const workbook = XLSX.read(data, {
            type: 'binary'
          })
          const wsname = workbook.SheetNames[0] // 取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) // 生成json表格内容
          const query = {
            url: '/BatchImport',
            method: 'post',
            data: { file: ws }
          }
          this.$fetchData(query)
            .then(res => {
              const defaultNotify = {
                message: res.data,
                icon: 'check_circle',
                color: 'green',
                position: 'top',
                timeout: 1500
              }
              Notify.create(defaultNotify)
            }).catch(e => {
              console.log(e)
            })
        } catch (e) {
          return false
        }
      }
      fileReader.readAsBinaryString(files[0])
    },
    handleUp () {
      // console.log(this.sheet)
    },
    onRejected (rejectedEntries) {
      this.$q.notify({
        type: 'negative',
        message: `${rejectedEntries.length} file(s) did not pass validation constraints`
      })
    },
    getAllSemesterYear () {
      const queryYear = {
        url: '/getAllSemesterServlet',
        methods: 'get'
      }
      this.$fetchData(queryYear).then(res => {
        if (res.data !== null) {
          console.log(res)
          this.semesterPreferred = res.data[res.data.length - 1]// 绑定的默认数据为最新的学期
          this.semesterOption = res.data// 将获取到的学期数据返回下拉框的选择里
        } else {
          this.$q.notify({
            icon: 'announcement',
            message: '获取记录为空',
            color: 'red',
            position: 'top',
            timeout: 1500
          })
        }
      }).catch(e => {
        console.log(e)
      })
    },
    onSubmit () {
      const query = {
        url: '/RecordAttendServlet',
        methods: 'get',
        params: {
          studentNumber: this.studentNumber,
          semesterId: this.semesterPreferred.value,
          week: this.week,
          typeId: this.typeId,
          times: this.times,
          note: this.note
        }
      }
      this.$fetchData(query).then(res => {
        console.log(res)
        const defaultNotify = {
          message: res.data,
          icon: 'warning',
          color: 'info',
          position: 'top',
          timeout: 1500
        }
        Notify.create(defaultNotify)
      }).catch(e => {
        console.log(e)
      })
    },
    onReset () {
      this.studentNumber = null
      this.semesterId = null
      this.week = null
      this.typeId = null
      this.times = null
      this.note = null
    }
  }
}
</script>

<style scoped>

</style>
